package com.server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

import com.entity.GamePool;
import org.springframework.stereotype.Component;


/**
 * @author zhengkai.blog.csdn.net
 */
@ServerEndpoint("/pipe")
@Component
public class WebSocketServer {

    private static int onlineCount = 0;

    /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<String,WebSocketServer>();

    /**  游戏池储存房主和房间号的对应关系*/
    private static Map<String, String[]> roomUser = new HashMap<String, String[]>();
    private static Map<String, String> userRoom = new HashMap<String, String>();

    public static Map<String, String[]> getRoomUser() {
        return roomUser;
    }

    public static Map<String, String> getUserRoom() {
        return userRoom;
    }

    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;

    /**接收userId*/
    private String userId="";

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        this.userId=session.getId();
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        String user = session.getId();
        if(webSocketMap.containsKey(user)){
            webSocketMap.remove(user);
            //从set中删除
            subOnlineCount();
        }
        if(userRoom.containsKey(user)) {
            String room = userRoom.get(user);
            String[] users = roomUser.get(room);
            if (users[0] != null && users[0].equals(user)) {
                users[0] = null;
            } else if (users[0] != null && users[1].equals(user)) {
                users[1] = null;
            }
            userRoom.remove(user);
            if (users[0] == null && users[1] == null) {
                roomUser.remove(room);
                GamePool.gmaePoll.remove(room);
            }
        }
    }

    @OnMessage
    public void onMessage(String room, Session session){
        String id = session.getId();
        String[] value = null;
        userRoom.put(id, room);
        if(roomUser.containsKey(room)){
            value = roomUser.get(room);
            if(value[0] == null){
                value[0] = id;
            } else if(value[1] == null){
                value[1] = id;
            }
        } else {
            value = new String[]{id, null};
            roomUser.put(room, value);
        }



    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String room, String message) throws IOException {
        String[] users = roomUser.get(room);
        for(String i : users){
            if(i != null) {
                webSocketMap.get(i).sendMessage(message);
            }
        }

    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
